package com.example.networkutil;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import org.xmlpull.v1.XmlPullParserException;
import com.example.suppliers.FirstActivity;
import utils.IOHandler;
import utils.XmlWorkersParser;
import Entity.WorkersDBEntity;
import android.os.AsyncTask;
import android.util.Log;


 public class DownloadWorkersTask extends AsyncTask<Object, Void, WorkersDBEntity> {
	  public static boolean downloadWorkersTask() throws InterruptedException, ExecutionException {
		   if (((NetworkReceiver.sPref.equals(NetworkReceiver.ANY)) && (NetworkReceiver.wifiConnected || NetworkReceiver.mobileConnected))
	                || ((NetworkReceiver.sPref.equals(NetworkReceiver.WIFI)) && (NetworkReceiver.wifiConnected))) {
				
	        	new DownloadWorkersTask().execute("").get();
	        
	        	if(FirstActivity.we!=null){
	        	Log.d("Test", "Done!");
	        	return true;}
	        	else{
	        		Log.d("Ftp", "Can't connect to FTP");
	        		return false;
	        		
	        	}
	        } else {
	        	Log.d("Network", "No Network");
				return false;
	        }
	   }
		@Override
		protected WorkersDBEntity doInBackground(Object... arg0) {
			// TODO Auto-generated method stub
			FirstActivity.we = readParse();
			return FirstActivity.we;
		}
		private WorkersDBEntity readParse(){
			if (FtpHandler.mFTPClient == null) {
				if (FtpHandler.ftpConnect()) {
					Log.d("mFTPClient", "Connected");
					
				}
				else {
					return null;
				}

			}
			InputStream is = FtpHandler.ftpDownload(FtpHandler.IN, "workers");
			if(is != null){
				XmlWorkersParser parser = new XmlWorkersParser();
				try {
					IOHandler.InputStreamToFile(is , "workers.xml");
					return parser.parse(IOHandler.FileToInputStream("workers.xml"));
					
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		} 
	   }

